<template>
    <div class="fullcompany">
        <div>
            <van-nav-bar title="填写订单" left-text="返回" left-arrow @click-left="onClickLeft" />
        </div>
        <div class="fullcompany-content">
            <div>
                <img src="http://mms2.baidu.com/it/u=1297891964,3964858050&fm=253&app=138&f=JPEG?w=60&h=60"
                    class="fullcompany_img">
            </div>
            <div>
                <span class="fullcompany_title">{{ service_title }}</span>
                <div class="fullcompany_des">
                    <span class="fullcompany_left">就医陪护 <span></span></span>
                </div>
            </div>
        </div>
        <div class="fullcompany_form">
            <van-field v-model="selectedHospital" is-link readonly name="picker" label="医院" placeholder="请选择医院"
                @click="showPicker1 = true" />
            <van-popup v-model:show="showPicker1" destroy-on-close position="bottom">
                <van-picker :columns="hospital_columns" :model-value="pickerValue1" @confirm="onConfirmHospital"
                    @cancel="showPicker1 = false" />
            </van-popup>

            <van-field v-model="selectedEscort" is-link readonly name="picker" label="指定陪诊人" placeholder="请选择陪诊员(选填)"
                @click="showPicker2 = true" />
            <van-popup v-model:show="showPicker2" destroy-on-close position="bottom">
                <van-picker :columns="escort_columns" :model-value="pickerValue2" @confirm="onConfirmEscort"
                    @cancel="showPicker2 = false" />
            </van-popup>

            <van-field v-model="selectedPatient" is-link readonly name="picker" label="指定就诊人" placeholder="请选择就诊人"
                @click="showPicker3 = true" />
            <van-popup v-model:show="showPicker3" destroy-on-close position="bottom">
                <van-picker :columns="patient_columns" :model-value="pickerValue3" @confirm="onConfirmPatient"
                    @cancel="showPicker3 = false" />
            </van-popup>

            <van-field v-model="selectedHopetime" is-link readonly name="calendar" label="期望就诊时间" placeholder="请选择就诊时间"
                @click="showCalendar = true" />
            <van-calendar v-model:show="showCalendar" @confirm="onConfirmHopetime" />


            <van-field v-model="selectedDepartment" is-link readonly name="picker" label="科室" placeholder="请选择科室"
                @click="showPicker4 = true" />
            <van-popup v-model:show="showPicker4" destroy-on-close position="bottom">
                <van-picker :columns="department_columns" :model-value="pickerValue4" @confirm="onConfirmDepartment"
                    @cancel="showPicker4 = false" />
            </van-popup>

            <van-field v-model="selectedAddress" placeholder="请输入接送地址" label="接送地址" />

            <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
            <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
                <van-coupon-list :coupons="coupons" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons"
                    @change="onChange" @exchange="onExchange" />
            </van-popup>

            <van-field name="uploader" label="资料上传（就诊卡、病例等）" class="uploader-field">
                <template #input>
                    <van-uploader v-model="upload_img" :after-read="afterRead" :max-count="1" />
                </template>
            </van-field>
        </div>

        <van-submit-bar :price="actualPrice * 100" text-align="left" label="实付：" button-text="立即支付"
            button-color="rgb(0, 170, 255)" @submit="onSubmit">
            <template #tip>
                <div class="tip-content">
                    <van-checkbox v-model="tip_checked" style="transform: scale(0.7);"></van-checkbox>
                    <span class=" black-text">我已认真阅读预约相关</span>
                    <span class="blue-text" @click="onClickLink">《服务条款同意书》</span>
                </div>
            </template>
        </van-submit-bar>

    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import * as qiniu from 'qiniu-js';
import { storeToRefs } from 'pinia';
import { useUserStore } from '../stores/store';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import http from '../http';

const route = useRoute();
const router = useRouter();
const service_title = route.query.serviceItem;
const service_price = route.query.servicePrice;
const couponValue = ref(0);
const actualPrice = ref(0);
const userStore = useUserStore();
const { hospitalList, userAccount } = storeToRefs(userStore);
let selectedHospital = ref('');
let selectedEscort = ref('');
let selectedPatient = ref('');
let selectedHopetime = ref('');
let selectedDepartment = ref('');
let selectedAddress = ref('');
let tip_checked = ref(false);
const pickerValue1 = ref([]);
const pickerValue2 = ref([]);
const pickerValue3 = ref([]);
const pickerValue4 = ref([]);
const showPicker1 = ref(false);
const showPicker2 = ref(false);
const showPicker3 = ref(false);
const showPicker4 = ref(false);
const showCalendar = ref(false);
const hospital_columns = ref([]);
const escort_columns = ref([]);
const patient_columns = ref([]);
const department_columns = ref([]);
const upload_img = ref([]);
const qiniu_img = ref('');
let token = ref('');
const getQiniuToken = () => {
    http.get('/patient/qiniu_token').then(res => {
        if (res.status === 200) {
            token.value = res.data.token
            console.log('token<<<<<', token.value);
        }
    }).catch(err => {
        console.log(err);
    })
};


const afterRead = (file) => {
    console.log('上传凭证', file);
    console.log('qiniu内容', file.file);
    console.log('文件格式', file.file.name);
    http.post('/patient/qiniu_download/', {
        key: file.file.name
    }).then(res => {
        if (res.status === 200) {
            console.log('图片地址成功', res.data.download_url);
            qiniu_img.value = res.data.download_url;
        }
    }).catch(err => {
        console.log("失败", err);
    })
    try {
        const config = {
            useCdnDomain: true, //使用 cdn 加速域名
            region: qiniu.region.z2, // 存储区域。华北 z0 华东 z1 华南 z2 北美 na0
        };
        const observable = qiniu.upload(file.file, file.file.name, token.value, config);
        const observer = {
            next(res) {
                console.log('上传进度', res.total.percent);
            },
            error(err) {
                console.log('文件上传失败', err);
            },
            complete(res) {
                console.log('文件上传成功', res);
            },
        };
        const subscription = observable.subscribe(observer); // 上传开始
        subscription.unsubscribe(); // 上传取消
    } catch (err) {
        console.log('获取上传凭证失败', err);
    }
};

const coupon = {
    available: 1,
    condition: '无门槛\n最多优惠20元',
    reason: '',
    value: 2000,
    name: '新人优惠券',
    startAt: 1733932800,
    endAt: 1735056000,
    valueDesc: '20',
    unitDesc: '元',
};

const coupons = ref([coupon]);
const showList = ref(false);
const chosenCoupon = ref(-1);

const onChange = (index) => {
    showList.value = false;
    chosenCoupon.value = index;
    const selectedCoupon = coupons.value[index];
    couponValue.value = selectedCoupon.value;
};

const onExchange = (code) => {
    coupons.value.push(coupon);
};

const disabledCoupons = [coupon];


const getHospitals = async () => {
    if (hospitalList.value.length > 0) {
        hospital_columns.value = hospitalList.value.map(hospital => ({
            text: hospital.name,
            value: hospital.name,
        }));
        console.log("----hospitals-----", hospital_columns.value);
    } else {
        console.log("获取医院信息出错:");
    }
};

const getEscorts = async () => {
    try {
        const response = await http.get('/patient/escortinfo/');
        const escorts = response.data.escorts;
        escort_columns.value = escorts.map(escort => ({
            text: escort.e_name,
            value: escort.e_name
        }));
        console.log("----escorts-----", escort_columns.value);
    } catch (error) {
        console.log("获取陪诊师信息出错:", error);
    }
};

const getPatients = async () => {
    try {
        const response = await http.get('/patient/patient/');
        console.log("就诊人信息", response.data.patients);
        const patients = response.data.patients;
        patient_columns.value = patients.map(patient => ({
            text: patient.name,
            value: patient.name,
        }));
        console.log("----patients-----", patient_columns.value);
    } catch (error) {
        console.log("获取陪诊师信息出错:", error);
    }
};


const getDepartment = async (hospitalName) => {
    try {
        const response = await http.get('/patient/department/', {
            params: {
                hospital_name: hospitalName
            }
        });
        const departments = response.data.departments;
        department_columns.value = departments.map(department => ({
            text: department.professional_department,
            value: department.professional_department
        }));
        console.log("----departments-----", department_columns.value);
    } catch (error) {
        console.log("获取科室信息出错:", error);
    }
};


onMounted(async () => {
    await getHospitals();
    await getEscorts();
    await getPatients();
    const defaultHospital = hospitalList.value.length > 0 ? hospitalList.value[0].name : '';
    if (defaultHospital) {
        await getDepartment(defaultHospital);
    };
    getQiniuToken();
});


const onConfirmHospital = ({ selectedValues, selectedOptions }) => {
    selectedHospital.value = selectedOptions[0]?.text;
    pickerValue1.value = selectedValues;
    showPicker1.value = false;
    const selectedHospitalName = selectedHospital.value;
    if (selectedHospitalName) {
        getDepartment(selectedHospitalName);
    }
};

const onConfirmEscort = ({ selectedValues, selectedOptions }) => {
    selectedEscort.value = selectedOptions[0]?.text;
    pickerValue2.value = selectedValues;
    showPicker2.value = false;
};

const onConfirmPatient = ({ selectedValues, selectedOptions }) => {
    selectedPatient.value = selectedOptions[0]?.text;
    pickerValue3.value = selectedValues;
    showPicker3.value = false;
};

const onConfirmDepartment = ({ selectedValues, selectedOptions }) => {
    selectedDepartment.value = selectedOptions[0]?.text;
    pickerValue4.value = selectedValues;
    showPicker4.value = false;
}

const onConfirmHopetime = (date) => {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    selectedHopetime.value = `${year}-${month}-${day}`;
    showCalendar.value = false;
};

const onClickLeft = () => history.back();

const validateRequiredFields = () => {
    const requiredFields = [
        selectedHospital.value,
        selectedEscort.value,
        selectedPatient.value,
        selectedDepartment.value,
        selectedHopetime.value,
        selectedAddress.value,
        couponValue.value,
        actualPrice.value
    ];
    for (const field of requiredFields) {
        if (field === null || field === '') {
            return { valid: false, message: '存在必填字段未填写，请检查' };
        }
    }
    if (!tip_checked.value) {
        return { valid: false, message: '请勾选同意《服务条款同意书》' };
    }
    return { valid: true, message: '' };
};

const onSubmit = () => {
    actualPrice.value = service_price - couponValue.value / 100;
    console.log("实付", actualPrice.value);
    const validationResult = validateRequiredFields();
    if (validationResult.valid) {
        const formdata = {
            user: userAccount.value,
            service_item: route.query.serviceItem,
            hospital: selectedHospital.value,
            escort: selectedEscort.value,
            patient: selectedPatient.value,
            department: selectedDepartment.value,
            expect_time: selectedHopetime.value,
            address: selectedAddress.value,
            coupon: couponValue.value / 100,
            price: actualPrice.value,
            data_upload: qiniu_img.value,
        };
        http.post('/patient/submitformdata/', formdata)
            .then(res => {
                console.log('提交订单成功', res.data);
                router.push('/index');
            })
            .catch(err => {
                console.log('提交订单失败', err);
            });
    } else {
        console.log(validationResult.message);
    }
};

</script>
<style scoped>
.fullcompany {
    background-color: rgb(245, 245, 245);
}

.fullcompany-content {
    position: relative;
    background-color: white;
    height: 80px;
    width: 90%;
    margin: 5% auto;
    border-radius: 5px;
}

.fullcompany_img {
    width: 40px;
    height: 40px;
    margin: 20px 5%;
}

.fullcompany_title {
    position: absolute;
    top: 20%;
    left: 30%;
    font-weight: 700;
}

.fullcompany_des {
    color: rgb(164, 163, 163);
}

.fullcompany_left {
    position: absolute;
    top: 50%;
    left: 30%;
    font-size: 14px;
}

.fullcompany_form {
    width: 90%;
    margin: 0 auto;
}


.uploader-field {
    --van-field-label-width: auto;
    --van-field-label-font-size: 12px;
    --van-field-label-text-align: left;
    display: flex;
    flex-direction: column;
}

.uploader-field .van-uploader {
    margin-top: 5px;
}

.tip-content {
    display: flex;
    align-items: center;
    justify-content: center;
}

.tip-checkbox {
    width: 20px;
}

.black-text {
    color: black;
}

.blue-text {
    color: rgb(0, 170, 255);
}
</style>
